package com.sina.shop.dao.address;

import com.sina.shop.dao.ShopDataSourceDao;
import com.sina.shop.domain.address.Address;
import com.sina.shop.domain.address.Status;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:地址管理实现类
 * 段浩杰   2018-02-05-11:59
 */
@Repository("addressDao")
public class AddressDaoImpl extends ShopDataSourceDao implements AddressDao {

    @Override
    public List<Address> getAddressListByAdminId(Long adminId) {
        String hql = "select new Address(id,province,city,country,street,zipCode,createTime,status) from Address a where a.admin.id= :adminId";
        return list(hql, new String[]{"adminId"}, new Object[]{adminId}, -1, -1);
    }

    @Override
    public Integer deleteAddress(Long id) {
        String hql = "delete from Address a where a.id = :id";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", id);

            return query.executeUpdate();
        });
    }

    @Override
    public int updateAddressStatusUse(Long id) {
        String hql = "update Address a set a.status=:status where a.id = :id";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            query.setParameter("status", Status.USE);
            return query.executeUpdate();
        });
    }

    @Override
    public int updateAddressStatusNot(Long aid) {
        String hql = "update Address a set a.status=:status where a.admin.id = :id and a.status = :statuss";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", aid);
            query.setParameter("status", Status.UN_USE);
            query.setParameter("statuss", Status.USE);
            return query.executeUpdate();
        });
    }
}
